from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps
from app.crud.crud_interaction import like_job, unlike_job, create_comment, get_comments_for_job

router = APIRouter()


@router.post("/jobs/{job_id}/like", response_model=schemas.GenerationJob)
def like_a_job(
    *,
    db: Session = Depends(deps.get_db),
    job_id: int,
    current_user: models.User = Depends(deps.get_current_user),
) -> any:
    """
    Like a job.
    """
    updated_job = like_job(db=db, user_id=current_user.id, job_id=job_id)
    if not updated_job:
        raise HTTPException(status_code=404, detail="Job not found")
    return updated_job


@router.delete("/jobs/{job_id}/like", response_model=schemas.GenerationJob)
def unlike_a_job(
    *,
    db: Session = Depends(deps.get_db),
    job_id: int,
    current_user: models.User = Depends(deps.get_current_user),
) -> any:
    """
    Unlike a job.
    """
    updated_job = unlike_job(db=db, user_id=current_user.id, job_id=job_id)
    if not updated_job:
        raise HTTPException(status_code=404, detail="Job not found")
    return updated_job


@router.post("/jobs/{job_id}/comments", response_model=schemas.Comment)
def create_a_comment(
    *,
    db: Session = Depends(deps.get_db),
    job_id: int,
    comment_in: schemas.CommentCreate,
    current_user: models.User = Depends(deps.get_current_user),
) -> any:
    """
    Create a comment for a job.
    """
    try:
        new_comment = create_comment(
            db=db, 
            user_id=current_user.id, 
            job_id=job_id,
            comment_in=comment_in
        )
        return new_comment
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))


@router.get("/jobs/{job_id}/comments", response_model=list[schemas.Comment])
def read_job_comments(
    *,
    db: Session = Depends(deps.get_db),
    job_id: int,
    skip: int = 0,
    limit: int = 100,
) -> any:
    """
    Get comments for a job.
    """
    comments = get_comments_for_job(db=db, job_id=job_id, skip=skip, limit=limit)
    return comments
